<?php

namespace app\modules\backend\controllers;

use app\models\Base;
use app\models\Activity;
use app\tools\Re;
use Yii;
use yii\helpers\Json;

class ActivityController extends BaseController
{
    /**
     * @param string $type
     * @return array
     */
    public function actionActivityList($type = ''){
        $page = Yii::$app->request->post('page', 0);
        $pid = Yii::$app->request->post('pid', 0);
        $activity_query = Activity::find()
            ->where(['status' => [0,1]]);
        $activity_list = $activity_query->orderBy("sort desc, created_at desc")->limit(Activity::PAGE_SIZE)->offset(Activity::PAGE_SIZE*$page)->all();
        $activity_data = [];
        if ($activity_list) {
            foreach ($activity_list as $v) {
                $activity_data[] = [
                    'id' => $v->id,
                    'good_id' => $v->good_id,
                    'good_name' => $v->good->name,
                    'cover' => $v->cover,
                    'sort' => $v->sort,
                    'status' => $v->status,
                    'created_time' => date("Y-m-d H:i", $v->created_at),
                ];
            }
        }
        return Re::data([
            'data' => $activity_data,
            'totalPage' => $activity_query->count(),
            'currentPage' => $page,
            'perPage' => Activity::PAGE_SIZE
        ]);
    }

    public function actionEditActivity(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        return $this->edit(Activity::class, $id, $post);
    }

    public function actionChangeActivityStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $activity = Activity::findOne($id);
        if (empty($activity)) {
            return Re::data(null, '品广告信息读取失败', Re::ERROR);
        }
        $activity->status =  $status;
        if (!$activity->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }
}
